package com.cardone.platform.configuration.action;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.Map.Entry;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.StringUtils;

import com.cardone.context.ContextHolder;
import com.cardone.context.action.Run3Action;
import com.cardone.platform.configuration.dto.DictionaryDto;
import com.cardone.platform.configuration.service.DictionaryService;

/**
 * bean属性名称支持
 *
 * @author fand.cardone
 *
 */
@Slf4j
public class CopyPropertiesBean2BeanForDictionaryAction implements Run3Action<Object, Object, Map<String, Object>> {
	@Override
	public void run(final Object source, final Object target, final Map<String, Object> parameters) {
		for (final Entry<String, Object> parameterEntry : parameters.entrySet()) {
			try {
				final Object objectDictionaryId = PropertyUtils.getProperty(source, parameterEntry.getKey());

				String dictionaryId = null;

				if (objectDictionaryId instanceof String) {
					dictionaryId = (String) objectDictionaryId;
				}

				String targetName = null;

				if (parameterEntry.getValue() instanceof String) {
					targetName = (String) parameterEntry.getValue();
				}

				if (StringUtils.isBlank(targetName)) {
					targetName = parameterEntry.getKey();
				}

				if (StringUtils.isBlank(dictionaryId)) {
					PropertyUtils.setProperty(target, targetName, null);

					continue;
				}

				final DictionaryDto findDictionary = DictionaryDto.newDictionary();

				findDictionary.setId(dictionaryId);

				final DictionaryDto dictionary = ContextHolder.getBean(DictionaryService.class).findById(DictionaryDto.class, findDictionary);

				if (dictionary == null) {
					PropertyUtils.setProperty(target, targetName, null);

					continue;
				}

				PropertyUtils.setProperty(target, targetName, dictionary.getName());
			} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
				CopyPropertiesBean2BeanForDictionaryAction.log.error(e.getMessage(), e);
			}
		}
	}
}